﻿Imports System.Globalization
Imports System.Threading
Imports System.Collections.Generic
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.Control
Imports System.Text

Partial Public Class Frm_ManageShifting
    Inherits System.Web.UI.Page

    Private clsGet As New ClassFunctionGetData
    Private clsFc As New ClassFunction
    Dim productArrayList As ArrayList
    Dim numberFormat As NumberFormatInfo
    Dim db As DB_Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        numberFormat = New NumberFormatInfo()
        numberFormat.NumberDecimalDigits = 3
        db = New DB_Class()
       

        If (Session("isFromSchedule") Is Nothing) Then
            btnCloseFromSchedule.Visible = False
            btnClose.Visible = True
        Else
            btnClose.Visible = False
            btnCloseFromSchedule.Visible = True
        End If
        productArrayList = New ArrayList()
        If Not IsPostBack Then
            ViewState("ShiftingClass") = New List(Of Shifting)()
            ViewState("isNewSchedule") = True
            ViewState("index") = ""
            If Not Session("Shifting") Is Nothing Then
                ViewState("Shifting") = Session("Shifting")
                If ViewState("Shifting") <> "" Then
                    Dim BookingNo As String = ViewState("Shifting")
                    Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(BookingNo)
                    LoadData(BookingNo)
                    lblBookingNo.Text = BookingNo
                    lblLayCanLayDay.Text = dsBooking.Tables(0).Rows(0).Item("Date_From") & " ถึง " & dsBooking.Tables(0).Rows(0).Item("Date_To")
                    If (dsBooking.Tables(0).Rows(0).Item("Booking_Date").ToString() <> "") Then
                        lblRequireDateTime.Text = dsBooking.Tables(0).Rows(0).Item("Booking_Date") & " : " & dsBooking.Tables(0).Rows(0).Item("Booking_Time")
                    Else
                        lblRequireDateTime.Text = " - "
                    End If
                    If (dsBooking.Tables(0).Rows(0).Item("Lay_Time").ToString() <> "" And dsBooking.Tables(0).Rows(0).Item("Lay_Time").ToString() <> "0") Then
                        lblLayTime.Text = dsBooking.Tables(0).Rows(0).Item("Lay_Time") & " Hours"
                    Else
                        lblLayTime.Text = " - "
                    End If
                    db = New DB_Class()
                    db.queryString = "select * from  Booking_Product where Booking_no='" & BookingNo & "' order by Product_no"
                    'msg.Text += db.queryString & "<br>"
                    Dim dtProduct As DataTable = db.getTable("Product")
                    Dim comodStr As New StringBuilder()
                    Dim vol As Double
                    For Each dr As DataRow In dtProduct.Rows
                        comodStr.Append(dr("Product_Name").ToString())
                        vol = CDbl(dr("Product_Amount").ToString())
                        comodStr.Append("  &nbsp;<span style='color:#1cb759'>" & vol.ToString("N", numberFormat))
                        comodStr.Append("</span>  " & dr("Product_Unit").ToString())
                        comodStr.Append("<br>")
                    Next
                    lbCommodity.Text = comodStr.ToString()
                    Dim productQty As Double = CDbl(dsBooking.Tables(0).Rows(0)("Product_Amount").ToString())
                    lbQty.Text = productQty.ToString("N", numberFormat) & " " & dsBooking.Tables(0).Rows(0)("Product_Unit")
                    lbVeselName.Text = dsBooking.Tables(0).Rows(0)("Vehicle_Text").ToString()
                End If
            End If
        End If
    End Sub
    Protected Function CloneBookingShiftingSchema() As DataTable
        db.queryString = "select TOP 1 * from Booking_Shifting"
        Dim dt As DataTable = db.getTable("bookingShift").Clone()
        dt.Columns.Add("Wharf", GetType(String))
        Return dt
    End Function
    Protected Function GetAllWharf(ByVal port As String) As DataTable
        db.queryString = "select * from Wharf where PORT='" & port & "'"
        Dim dt As DataTable = db.getTable("wharf")
        Return dt
    End Function

    Protected Sub btnClose_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClose.Click
        Session("Shifting") = Nothing
        Dim redirect As String = Request.Url.Host & Page.ResolveUrl("~/frm_PortSchedulerNew.aspx") & Request.Url.Query
        'If Not (Session("isFromSchedule") Is Nothing) Then
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " parent.closeModalShifting();", True)
        'Else
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " parent.closeModal('H');", True)
        'End If

    End Sub

    Private Sub LoadData(ByVal BookingNo As String)
        'Dim dtShifting As DataSet = clsGet.Get_BookingShifting(BookingNo)
        db.queryString = "select * from BookingWharf bw left outer join Booking b on bw.Booking_no=b.Booking_no "
        db.queryString &= " left outer join Wharf w on bw.BookingWharf=w.BookingWharf"
        db.queryString &= " where bw.Booking_no='" & BookingNo & "'"
        Dim dtWharf As DataTable = db.getTable("wharf")
        Dim dtShift As DataTable = CloneBookingShiftingSchema()

        If (dtWharf.Rows.Count < 1) Then
            ViewState("isNewSchedule") = True
        Else
            ViewState("isNewSchedule") = False
        End If
        If (dtWharf.Rows.Count > 0) Then
            Dim rowShift As DataRow = dtShift.NewRow()
            Dim rowWharf As DataRow = dtWharf.Rows(0)
            'rowShift("Product_volume") = rowWharf("Product_Amount").ToString()
            rowShift("Shifting_ID") = "00000"
            rowShift("Wharf") = rowWharf("Wharf").ToString()
            rowShift("BookingWharf") = rowWharf("BookingWharf").ToString()
            rowShift("DateStart") = rowWharf("DateStart").ToString()
            rowShift("DateEnd") = rowWharf("DateEnd").ToString()
            rowShift("TimeStart") = rowWharf("TimeStart").ToString()
            rowShift("TimeEnd") = rowWharf("TimeEnd").ToString()
            rowShift("Remark") = rowWharf("Remark").ToString()
            rowShift("PORT") = rowWharf("PORT").ToString()
            ViewState("PORT") = rowWharf("PORT").ToString()
            dtShift.Rows.Add(rowShift)
        Else
            Dim rowShift As DataRow = dtShift.NewRow()
            db.queryString = "select PORT from Booking where Booking_no='" & BookingNo & "'"
            Dim dtPort As DataTable = db.getTable("port")
            rowShift("Shifting_ID") = "00000"
            rowShift("PORT") = dtPort.Rows(0)("PORT").ToString()
            ViewState("PORT") = dtPort.Rows(0)("PORT").ToString()
            dtShift.Rows.Add(rowShift)
        End If

        db.queryString = "select * from Booking_Shifting bs left outer join Booking b on bs.Booking_no=b.Booking_no"
        db.queryString &= " left outer join Wharf w on bs.BookingWharf=w.BookingWharf"
        db.queryString &= " where bs.Booking_no='" & BookingNo & "'"
        Dim dtShift2 As DataTable = db.getTable("shifting2")
        If (dtShift2.Rows.Count > 0) Then
            For Each dr As DataRow In dtShift2.Rows
                Dim rowShift As DataRow = dtShift.NewRow()
                rowShift("Shifting_ID") = dr("Shifting_ID").ToString()
                rowShift("Wharf") = dr("Wharf").ToString()
                rowShift("BookingWharf") = dr("BookingWharf").ToString()
                rowShift("DateStart") = dr("DateStart").ToString()
                rowShift("DateEnd") = dr("DateEnd").ToString()
                rowShift("TimeStart") = dr("TimeStart").ToString()
                rowShift("TimeEnd") = dr("TimeEnd").ToString()
                rowShift("Remark") = dr("Remark").ToString()
                rowShift("PORT") = dr("PORT").ToString()
                ViewState("PORT") = dr("PORT").ToString()
                dtShift.Rows.Add(rowShift)
            Next
        End If

      

        gridShifting.DataSource = dtShift
        gridShifting.DataBind()
        ViewState("dtShift") = dtShift
    End Sub

    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "")
        End If
    End Sub

    Private Sub gridShifting_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridShifting.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then


            Dim BookingNo As String = ViewState("Shifting")
            Dim Shifting_ID As String = gridShifting.DataKeys(e.Row.RowIndex)("Shifting_ID").ToString()


            Dim ddlWharfTmp As DropDownList = CType(e.Row.FindControl("ddlWharf"), DropDownList)
            Dim port As String = ViewState("PORT").ToString()
            ddlWharfTmp.DataSource = GetAllWharf(port)
            ddlWharfTmp.DataTextField = "Wharf"
            ddlWharfTmp.DataValueField = "BookingWharf"
            ddlWharfTmp.DataBind()

            Dim wharfId As String = gridShifting.DataKeys(e.Row.RowIndex)("BookingWharf").ToString()

            'Dim ddlWharfTmp As DropDownList = CType(e.Row.FindControl("ddlWharf"), DropDownList)
            'ddlWharfTmp.DataSource = GetAllWharf()
            'ddlWharfTmp.DataTextField = "Wharf"
            'ddlWharfTmp.DataValueField = "BookingWharf"
            'ddlWharfTmp.DataBind()


            If (Shifting_ID <> "") Then
                Dim wharfName As String = gridShifting.DataKeys(e.Row.RowIndex)("Wharf").ToString()
                If (wharfId <> "") Then
                    ddlWharfTmp.ClearSelection()
                    ddlWharfTmp.Items.FindByValue(wharfId).Selected = True
                    'ddlWharfTmp.Enabled = False
                Else
                    ddlWharfTmp.Items.Insert(0, New ListItem("- เลือก Wharf -", ""))
                End If

                Try
                    Dim txtDateTmp As TextBox = CType(e.Row.FindControl("txtDate"), TextBox)
                    Dim dateStartStr As String = gridShifting.DataKeys(e.Row.RowIndex)("DateStart").ToString()
                    Dim dateStart As Date = Date.ParseExact(dateStartStr, "dd/MM/yyyy", New CultureInfo("en-US"))
                    txtDateTmp.Text = dateStart.ToString("dd MMM yyyy")
                    'txtDateTmp.Enabled = False
                    Dim calendarDateStart As AjaxControlToolkit.CalendarExtender = CType(e.Row.FindControl("CalendarExtender1"), AjaxControlToolkit.CalendarExtender)
                    calendarDateStart.CssClass = "hide-calendar"

                    Dim txtDateToTmp As TextBox = CType(e.Row.FindControl("txtDateTo"), TextBox)
                    Dim dateEndStr As String = gridShifting.DataKeys(e.Row.RowIndex)("DateEnd").ToString()
                    Dim dateEnd As Date = Date.ParseExact(dateEndStr, "dd/MM/yyyy", New CultureInfo("en-US"))
                    txtDateToTmp.Text = dateEnd.ToString("dd MMM yyyy")
                    'txtDateToTmp.Enabled = False
                    Dim calendarDateEnd As AjaxControlToolkit.CalendarExtender = CType(e.Row.FindControl("CalendarExtender2"), AjaxControlToolkit.CalendarExtender)
                    calendarDateEnd.CssClass = "hide-calendar"

                Catch ex As Exception

                End Try
                Dim txtTimeBookingStartTmp As TextBox = CType(e.Row.FindControl("txtTimeBookingStart"), TextBox)
                Dim txtTimeBookingEndTmp As TextBox = CType(e.Row.FindControl("txtTimeBookingEnd"), TextBox)
                'txtTimeBookingStartTmp.Enabled = False
                'txtTimeBookingEndTmp.Enabled = False
            Else
                ddlWharfTmp.Items.Insert(0, New ListItem("- เลือก Wharf -", ""))
            End If
        End If
    End Sub
    Protected Sub gridShifting_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridShifting.RowCreated
        db = New DB_Class()
        If (e.Row.DataItemIndex > -1 And e.Row.RowType = DataControlRowType.DataRow) Then
           

            Dim Shifting_ID As String = gridShifting.DataKeys(e.Row.RowIndex)("Shifting_ID").ToString()
            ' msg.Text &= Shifting_ID & "<br>"
            Dim BookingNo As String = ViewState("Shifting")
           
            'Dim isOldData As Boolean = False
            'If (Shifting_ID <> "") Then
            '    isOldData = True
            'End If
            Dim volumCell As TableCell = e.Row.Cells(2)
            Dim productCell As TableCell = e.Row.Cells(1)
            ''''''''''''''''''Product จากท่าหลัก'''''''''''''''''''''''''''
            If (Shifting_ID = "00000") Then
                Dim BookingWharf As String = gridShifting.DataKeys(e.Row.RowIndex)("BookingWharf").ToString()
                db.queryString = "select * from BookingWharf_Product bwp left outer join Product p on bwp.Product_no=p.Product_no " _
                            & " where Booking_no='" & BookingNo & "' and BookingWharf='" & BookingWharf & "'"
                Dim queryStrTmp As String = db.queryString
                ''''''''''''''' หา product ที่ยังไม่ได้ถูกจัด หรือ เพิ่มเข้ามาใหม่ '''''''''''''''''''''
                Dim dtProductNotin As DataTable = getWhereProductNotin(db.queryString)
                db.queryString = queryStrTmp
                Dim dtBookingWharfProduct As DataTable = db.getTable("BookingWharfProduct")
                'dtBookingWharfProduct.Merge(dtProductNotin)
                If (dtProductNotin.Rows.Count > 0) Then
                    For Each dr As DataRow In dtProductNotin.Rows
                        Dim drTmp As DataRow = dtBookingWharfProduct.NewRow()
                        drTmp("Product_no") = dr("Product_no").ToString()
                        drTmp("Product_volume") = dr("Product_Amount").ToString()
                        drTmp("Product_name") = dr("Product_name").ToString()
                        drTmp("BookingWharf") = ""
                        dtBookingWharfProduct.Rows.Add(drTmp)
                    Next
                End If
                dtBookingWharfProduct.DefaultView.Sort = "Product_no ASC"
                dtBookingWharfProduct = dtBookingWharfProduct.DefaultView.ToTable()
                
                ''''''''''''มี ท่าหลักหรือไม่ ถ้าไม่มีจะนำ Product ทั้งหมดมาแสดง'''''''''''''''''''''
                If (dtBookingWharfProduct.Rows.Count > 0) Then
                    
                    If (dtBookingWharfProduct.Rows.Count > 1) Then 'ถ้ามี Product มากกว่า 1 ให้แสดงเป็น Checkbox
                        Dim proList As New CheckBoxList()
                        proList.ID = "product"
                        For Each drBookingWharfPro As DataRow In dtBookingWharfProduct.Rows
                            Dim proListItem As New ListItem()
                            Dim proId As String = drBookingWharfPro("Product_no").ToString()
                            proListItem.Value = proId
                            proListItem.Text = drBookingWharfPro("Product_name").ToString()
                            If (drBookingWharfPro("BookingWharf").ToString() <> "") Then
                                proListItem.Selected = True
                            End If
                            proList.Items.Add(proListItem)

                            Dim txtVolPro As New TextBox()
                            txtVolPro.Width = 70
                            txtVolPro.ID = "vol" & proId
                            txtVolPro.Text = drBookingWharfPro("Product_volume").ToString()
                            Dim brLiteral As New LiteralControl()
                            brLiteral.Text = "<br>"
                            volumCell.Controls.Add(txtVolPro)
                            volumCell.Controls.Add(brLiteral)

                        Next
                        productCell.Controls.Add(proList)
                    ElseIf (dtBookingWharfProduct.Rows.Count = 1) Then
                        Dim proLabel As New Label()
                        proLabel.ID = "product"
                        proLabel.Text = dtBookingWharfProduct.Rows(0)("Product_name").ToString()
                        Dim proIdHide As New HiddenField()
                        proIdHide.ID = "proIdHide"
                        proIdHide.Value = dtBookingWharfProduct.Rows(0)("Product_no").ToString()
                        productCell.Controls.Add(proLabel)
                        productCell.Controls.Add(proIdHide)
                        Dim txtVolPro As New TextBox()
                        txtVolPro.Width = 70
                        txtVolPro.ID = "vol"
                        txtVolPro.Text = dtBookingWharfProduct.Rows(0)("Product_volume").ToString()
                        volumCell.Controls.Add(txtVolPro)
                    End If

                Else
                    LoadNewProduct(e)
                    If (e.Row.RowIndex = 0 And ViewState("isNewSchedule")) Then
                        Dim imgDelTmp As ImageButton = CType(e.Row.FindControl("imgdelete"), ImageButton)
                        imgDelTmp.ImageUrl = "~/Image/cancel-24-disable.gif"
                        imgDelTmp.Enabled = False
                    End If
                End If
            ElseIf (Shifting_ID <> "00000" And Shifting_ID <> "") Then
                ''''''''''''''''''''''''''Product จากการ Shifting''''''''''''''''''''''''''''''''''''''
                db.queryString = "select * from Booking_Shifting_Product bsp left outer join Product p on bsp.Product_no=p.Product_no " _
                                & " where Shifting_ID='" & Shifting_ID & "'"
                Dim dtPro2 As DataTable = db.getTable("pro2")
                Dim dtProductNotin As DataTable = getWhereProductNotin(db.queryString)
                If (dtProductNotin.Rows.Count > 0) Then
                    For Each dr As DataRow In dtProductNotin.Rows
                        Dim drTmp As DataRow = dtPro2.NewRow()
                        drTmp("Product_no") = dr("Product_no").ToString()
                        drTmp("Product_name") = dr("Product_name").ToString()
                        drTmp("Product_volume") = dr("Product_Amount").ToString()
                        drTmp("Shifting_Product_ID") = ""
                        dtPro2.Rows.Add(drTmp)
                    Next
                End If
                dtPro2.DefaultView.Sort = "Product_no ASC"
                dtPro2 = dtPro2.DefaultView.ToTable()
                If (dtPro2.Rows.Count > 1) Then
                    Dim proList As New CheckBoxList()
                    proList.ID = "product"
                    For Each drPro2 As DataRow In dtPro2.Rows
                        Dim proItem As New ListItem() With { _
                            .Value = drPro2("Product_no").ToString(), _
                            .Text = drPro2("Product_name").ToString() _
                        }
                        If (drPro2("Shifting_Product_ID").ToString() <> "") Then
                            proItem.Selected = True
                        End If
                        proList.Items.Add(proItem)
                        Dim txtVolPro As New TextBox()
                        txtVolPro.Width = 70
                        txtVolPro.ID = "vol" & drPro2("Product_no")
                        If (drPro2("Shifting_Product_ID").ToString() <> "") Then
                            txtVolPro.Text = drPro2("Product_volume").ToString()
                        End If

                        Dim brLiteral As New LiteralControl()
                        brLiteral.Text = "<br>"
                        volumCell.Controls.Add(txtVolPro)
                        volumCell.Controls.Add(brLiteral)
                    Next
                    productCell.Controls.Add(proList)
                ElseIf (dtPro2.Rows.Count = 1) Then
                    Dim lbPro As New Label()
                    lbPro.ID = "product"
                    lbPro.Text = dtPro2.Rows(0)("Product_name").ToString()
                    productCell.Controls.Add(lbPro)
                    Dim proHideId As New HiddenField()
                    proHideId.ID = "proIdHide"
                    proHideId.Value = dtPro2.Rows(0)("Product_no").ToString()
                    productCell.Controls.Add(proHideId)
                    Dim txtVolPro As New TextBox()
                    txtVolPro.ID = "vol"
                    txtVolPro.Text = dtPro2.Rows(0)("Product_volume").ToString()
                    txtVolPro.Width = 70
                    volumCell.Controls.Add(txtVolPro)
                End If
            ElseIf (Shifting_ID = "") Then
                LoadNewProduct(e)
            End If
       
        End If
    End Sub
    Protected Function getWhereProductNotin(ByVal queryStr As String) As DataTable
        Dim where As String = ""
        Dim BookingNo As String = ViewState("Shifting")
        Dim db2 = New DB_Class()
        db2.queryString = queryStr
        Dim dtProduct As DataTable = db2.getTable("pro")
        Dim dtTmp As DataTable = dtProduct.Clone()
        Dim dtProductNotin As New DataTable()
        Dim proArr As New ArrayList()
        If (dtProduct.Rows.Count > 0) Then
            For Each drProduct As DataRow In dtProduct.Rows
                proArr.Add(drProduct("Product_no").ToString())
            Next
            where = String.Join("','", proArr.ToArray(GetType(String)))
            db2.queryString = "select Booking_no,Product_no,Product_name,Product_Amount " _
                            & "from  Booking_Product where Booking_no='" & BookingNo & "'"
            db2.queryString &= " and Product_no not in('" & where & "') order by Product_no"
            dtProductNotin = db2.getTable("p")
            'If (dtProductNotin.Rows.Count > 0) Then
            '    For Each dr As DataRow In dtProductNotin.Rows
            '        Dim drTmp As DataRow = dtTmp.NewRow()
            '        drTmp("Product_no") = dr("Product_no").ToString()
            '        drTmp("Product_volume") = dr("Product_Amount").ToString()
            '        drTmp("Product_name") = dr("Product_name").ToString()
            '        drTmp("BookingWharf") = ""
            '        dtTmp.Rows.Add(drTmp)
            '    Next
            'End If
        End If
        Return dtProductNotin
    End Function
    Protected Sub LoadNewProduct(ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)

        Dim volumCell As TableCell = e.Row.Cells(2)
        Dim productCell As TableCell = e.Row.Cells(1)

        Dim BookingNo As String = ViewState("Shifting")
        Dim Shifting_ID As String = gridShifting.DataKeys(e.Row.RowIndex)("Shifting_ID").ToString()
        db.queryString = "select * from  Booking_Product where Booking_no='" & BookingNo & "' order by Product_no"
        Dim dtProduct As DataTable = db.getTable("Product")
        If (dtProduct.Rows.Count > 1) Then
            Dim proList As New CheckBoxList()
            proList.ID = "product"
            For Each drPro As DataRow In dtProduct.Rows
                Dim txtVolPro As New TextBox()
                txtVolPro.ID = "vol" & drPro("Product_no")
                If (Shifting_ID = "00000") Then
                    txtVolPro.Text = drPro("Product_Amount").ToString()
                Else
                    txtVolPro.Text = String.Empty
                End If
                txtVolPro.Width = 70
                Dim brLiteral As New LiteralControl()
                brLiteral.Text = "<br>"
                volumCell.Controls.Add(txtVolPro)
                volumCell.Controls.Add(brLiteral)

                Dim wharfId As String = gridShifting.DataKeys(e.Row.RowIndex)("BookingWharf").ToString()
                If (wharfId <> "" And Not IsPostBack) Then
                    Dim listProItem As New ListItem()
                    listProItem.Value = drPro("Product_no").ToString()
                    listProItem.Text = drPro("Product_name").ToString()
                    listProItem.Selected = True
                    ' listProItem.Enabled = False
                    proList.Items.Add(listProItem)
                Else
                    proList.Items.Add(New ListItem(drPro("Product_name").ToString(), drPro("Product_no").ToString()))
                End If
            Next
            productCell.Controls.Add(proList)
        ElseIf (dtProduct.Rows.Count = 1) Then
            Dim txtVolPro As New TextBox()
            txtVolPro.ID = "vol"
            If (Shifting_ID = "00000") Then
                txtVolPro.Text = dtProduct.Rows(0)("Product_Amount").ToString()
            Else
                txtVolPro.Text = String.Empty
            End If

            txtVolPro.Width = 70
            volumCell.Controls.Add(txtVolPro)
            Dim lbPro As New Label()
            lbPro.ID = "product"
            lbPro.Text = dtProduct.Rows(0)("Product_name").ToString()
            Dim hideProId As New HiddenField()
            hideProId.ID = "proIdHide"
            hideProId.Value = dtProduct.Rows(0)("Product_no").ToString()
            productCell.Controls.Add(lbPro)
            productCell.Controls.Add(hideProId)
        End If
    End Sub
    Protected Function CheckEmpty(ByVal shiftingList As List(Of Shifting)) As Boolean
        'If(shifting.
        ' Dim hasProduct As Boolean = False
        Dim x As String = ViewState("isNewSchedule").ToString()
        Dim Empty As Boolean = False
        If (shiftingList.Count > 1) Then
            For Each shifting As Shifting In shiftingList
                Dim hasProAndVol As Boolean = True
                If (shifting.DateStart <> "" Or shifting.DateEnd <> "" Or shifting.TimeStart <> "" Or shifting.TimeEnd <> "" Or shifting.WharfID <> "" Or shifting.Product.Length > 0) Then
                    If (shifting.Product.Length > 0) Then
                        For Each proItem As Product In shifting.Product
                            If (proItem.ProductID = "" Or proItem.ProductVolume = "") Then
                                hasProAndVol = False
                                Exit For
                            End If

                        Next
                        If (Not hasProAndVol) Then
                            Empty = True
                            Exit For
                        End If
                    Else
                        Empty = True
                        Exit For
                    End If
                    If (shifting.DateStart = "" Or shifting.DateEnd = "" Or shifting.TimeStart = "" Or shifting.TimeEnd = "" Or shifting.WharfID = "") Then
                        Empty = True
                        Exit For
                    End If
                Else
                    If (shiftingList.Count > 1) Then
                        Empty = False
                    End If
                End If
            Next
        ElseIf (shiftingList.Count = 1) Then
            Dim shifting As Shifting = shiftingList(0)
            If (shifting.DateStart = "" Or shifting.DateEnd = "" Or shifting.TimeStart = "" Or shifting.TimeEnd = "" Or shifting.WharfID = "" Or shifting.Product.Length < 1) Then
                Empty = True
            Else
                If (shifting.Product.Length > 0) Then
                    For Each pro As Product In shifting.Product
                        If (pro.ProductID = "" Or pro.ProductVolume = "") Then
                            Empty = True
                            Exit For
                        End If
                    Next
                End If
            End If
        Else
            If (ViewState("isNewSchedule")) Then
                Empty = True
            Else
                Empty = False
            End If
        End If
        
        Return Empty
    End Function

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click

        msg.Text = ""
        Dim BookingNo As String = ViewState("Shifting")
        Dim User_Create As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") _
        & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
        'Find never shift and shifted
        'For Each gvr0 As GridViewRow In gridShifting.Rows
        '    Dim pro0 = gvr0.FindControl("product")

        'Next
        Dim listShifting As New List(Of Shifting)
        Dim c As Integer = gridShifting.Rows.Count
        For Each gvr As GridViewRow In gridShifting.Rows
            Dim shiftingId As String = gridShifting.DataKeys(gvr.RowIndex)("Shifting_ID").ToString()
            Dim port As String = ViewState("PORT").ToString()
            If (gvr.RowType = DataControlRowType.DataRow) Then
                Dim pro = gvr.FindControl("product")

                Dim shiftingItem As New Shifting()

                Dim txtDateTmp As TextBox = CType(gvr.FindControl("txtDate"), TextBox)
                Dim txtTimeBookingStartTmp As TextBox = CType(gvr.FindControl("txtTimeBookingStart"), TextBox)
                Dim txtDateToTmp As TextBox = CType(gvr.FindControl("txtDateTo"), TextBox)
                Dim txtTimeBookingEndTmp As TextBox = CType(gvr.FindControl("txtTimeBookingEnd"), TextBox)
                Dim txtRemarkTmp As TextBox = CType(gvr.FindControl("txtRemark"), TextBox)
                Dim ddlWharfTmp As DropDownList = CType(gvr.FindControl("ddlWharf"), DropDownList)

                shiftingItem.ShiftingID = shiftingId
                shiftingItem.WharfID = ddlWharfTmp.SelectedValue
                shiftingItem.DateStart = txtDateTmp.Text
                shiftingItem.TimeStart = txtTimeBookingStartTmp.Text
                shiftingItem.DateEnd = txtDateToTmp.Text
                shiftingItem.TimeEnd = txtTimeBookingEndTmp.Text
                shiftingItem.Remark = txtRemarkTmp.Text
                shiftingItem.PortType = port

                Dim products As New List(Of Product)
                If (TypeOf (pro) Is CheckBoxList) Then

                    Dim proList As CheckBoxList = CType(pro, CheckBoxList)
                    For Each proItem As ListItem In proList.Items
                        If (proItem.Selected) Then
                            Dim product As New Product()
                           
                            Dim proNo As String = proItem.Value
                            product.ProductID = proNo
                            Dim txtVol As TextBox = CType(gvr.FindControl("vol" & proNo), TextBox)
                            Dim vol As String = txtVol.Text
                            product.ProductVolume = vol
                            products.Add(product)
                            ' msg.Text &= ": " & txtVol.Text & "<br>"
                        End If
                    Next
                    shiftingItem.Product = products.ToArray()
                ElseIf (TypeOf (pro) Is Label) Then
                    Dim proidhide As HiddenField = CType(gvr.FindControl("proIdHide"), HiddenField)
                    Dim proVol As TextBox = CType(gvr.FindControl("vol"), TextBox)
                    Dim product As New Product()
                    product.ProductID = proidhide.Value
                    product.ProductVolume = proVol.Text
                    products.Add(product)
                    shiftingItem.Product = products.ToArray()
                End If
                listShifting.Add(shiftingItem)
            End If
        Next
        Dim x As Boolean = CheckEmpty(listShifting)
        If (Not CheckEmpty(listShifting)) Then
            db = New DB_Class()
            db.queryString = "delete from BookingWharf where Booking_no='" & BookingNo & "'"
            db.delete()
            db.queryString = "delete from BookingWharf_Product where Booking_no='" & BookingNo & "'"
            db.delete()
            db.queryString = "delete from Booking_Shifting where Booking_no='" & BookingNo & "'"
            db.delete()
            db.queryString = "delete from Booking_Shifting_Product where Booking_no='" & BookingNo & "'"
            db.delete()
            Dim listShiftingCount As Integer = listShifting.Count
            For Each shiftItem As Shifting In listShifting
                If (shiftItem.WharfID <> "") Then
                    Dim dateStart, dateEnd As Date

                    If (shiftItem.DateStart <> "") Then
                        dateStart = Date.ParseExact(shiftItem.DateStart, "dd MMM yyyy", New CultureInfo("en-US"))
                    End If
                    If (shiftItem.DateEnd <> "") Then
                        dateEnd = Date.ParseExact(shiftItem.DateEnd, "dd MMM yyyy", New CultureInfo("en-US"))
                    End If
                    If (shiftItem.ShiftingID = "00000" Or listShiftingCount = 1) Then
                        ' Dim shiftingId As String = db.GeneratID("BookingWharf", "BookingWharf")

                        db.queryString = "insert into BookingWharf (Booking_no,BookingWharf,Date_From," _
                                      & "Date_To,DateStart,DateEnd,TimeStart,TimeEnd,Remark,Confirm_Time,User_Create,Shift_Booking,Note)"
                        db.queryString &= " values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}')"
                        db.queryString = String.Format(db.queryString, BookingNo, shiftItem.WharfID, dateStart.ToString("dd MMM yyyy") _
                                                       , dateEnd.ToString("dd MMM yyyy"), dateStart.ToString("dd/MM/yyyy"), dateEnd.ToString("dd/MM/yyyy") _
                                                       , shiftItem.TimeStart, shiftItem.TimeEnd, shiftItem.Remark, "N", User_Create, "", shiftItem.Note)
                        db.insertUpdate()

                        For Each p As Product In shiftItem.Product
                            db.queryString = "insert into BookingWharf_Product (Booking_no,BookingWharf,Product_no,Product_volume)"
                            db.queryString &= " values('{0}','{1}','{2}','{3}')"
                            db.queryString = String.Format(db.queryString, BookingNo, shiftItem.WharfID, p.ProductID, p.ProductVolume)
                            db.insertUpdate()
                        Next
                    ElseIf ((shiftItem.ShiftingID = "" Or shiftItem.ShiftingID <> "00000") And listShiftingCount > 1) Then
                        'Add New Shifting
                        Dim shiftingId As String = db.GeneratID("Booking_Shifting", "Shifting_ID")

                        db.queryString = "insert into Booking_Shifting (Shifting_ID,Booking_No,BookingWharf,DateStart,DateEnd,TimeStart" _
                                        & ",TimeEnd,Remark,Confirm_Time,Note,PORT)"
                        db.queryString &= " values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')"
                        db.queryString = String.Format(db.queryString, shiftingId, BookingNo, shiftItem.WharfID, dateStart.ToString("dd/MM/yyyy"), dateEnd.ToString("dd/MM/yyyy") _
                                                       , shiftItem.TimeStart, shiftItem.TimeEnd, shiftItem.Remark, "N", shiftItem.Note, shiftItem.PortType)
                        db.insertUpdate()

                        For Each p As Product In shiftItem.Product
                            Dim shiftinProductId As String = db.GeneratID("Booking_Shifting_Product", "Shifting_Product_ID")
                            db.queryString = "insert into Booking_Shifting_Product (Shifting_Product_ID,Booking_no,Shifting_ID,Product_no,Product_volume)"
                            db.queryString &= " values('{0}','{1}','{2}','{3}','{4}')"
                            db.queryString = String.Format(db.queryString, shiftinProductId, BookingNo, shiftingId, p.ProductID, p.ProductVolume)
                            db.insertUpdate()
                        Next

                    End If
                End If
               
            Next

            'Dim redirect As String = "./frm_PortSchedulerNew.aspx" & Request.Url.Query
            ' ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " parent.closeModal('H');", True)
            Dim scriptToClose As String = ""
            If (Session("isFromSchedule") Is Nothing) Then
                scriptToClose = "parent.closeModal('H');"
                Session("Shifting") = Nothing
            Else
                scriptToClose = "parent.closeModalShifting();"
            End If

            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('บันทึกข้อมูลสำเร็จ');" & scriptToClose, True)
        Else
            ' If (ViewState("isNewSchedule")) Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('กรุณากรอกข้อมูลให้ครบ');", True)
            'Else
            'Dim scriptToClose As String = ""
            'If (Session("isFromSchedule") Is Nothing) Then
            '    scriptToClose = "parent.closeModal('H');"
            '    Session("Shifting") = Nothing
            'Else
            '    scriptToClose = "parent.closeModalShifting();"
            'End If
            'db = New DB_Class()
            'db.queryString = "delete from BookingWharf where Booking_no='" & BookingNo & "'"
            'db.delete()
            'db.queryString = "delete from BookingWharf_Product where Booking_no='" & BookingNo & "'"
            'db.delete()
            'db.queryString = "delete from Booking_Shifting where Booking_no='" & BookingNo & "'"
            'db.delete()
            'db.queryString = "delete from Booking_Shifting_Product where Booking_no='" & BookingNo & "'"
            'db.delete()
            'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('บันทึกข้อมูลสำเร็จ');" & scriptToClose, True)
            'End If

            'Exit Sub
        End If
        
        
    End Sub

    Private Function checkGridValue()
        Dim dt As DataTable = CreateDataTable()
        For i As Integer = 0 To gridShifting.Rows.Count - 1
            Dim chk As CheckBox = CType(gridShifting.Rows(i).FindControl("chkSelect"), CheckBox)
            Dim ddlWharfg As DropDownList = CType(gridShifting.Rows(i).FindControl("ddlWharf"), DropDownList)
            If (ddlWharfg.SelectedValue = "0") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Wharf ของ Booking no. " & gridShifting.DataKeys(i).Values("Booking_no") & "" & "');", True)
                Return False
            End If
            Dim txtDateg As TextBox = CType(gridShifting.Rows(i).FindControl("txtDate"), TextBox)
            Dim txtDateTog As TextBox = CType(gridShifting.Rows(i).FindControl("txtDateTo"), TextBox)
            Dim txtTimeStart As TextBox = CType(gridShifting.Rows(i).FindControl("txtTimeBookingStart"), TextBox)
            Dim txtTimeEnd As TextBox = CType(gridShifting.Rows(i).FindControl("txtTimeBookingEnd"), TextBox)
            Dim txtRemark As TextBox = CType(gridShifting.Rows(i).FindControl("txtRemark"), TextBox)
            If (txtDateg.Text.Trim() = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุวันที่เริ่มต้นของ Booking no. " & gridShifting.DataKeys(i).Values("Booking_no") & "" & "');", True)
                Return False
            End If
            If (txtDateTog.Text.Trim() = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุวันที่สิ้นสุดของ Booking no. " & gridShifting.DataKeys(i).Values("Booking_no") & "" & "');", True)
                Return False
            End If
            If (txtTimeStart.Text.Trim().Replace(":", "") = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเวลาเริ่มต้นของ Booking no. " & gridShifting.DataKeys(i).Values("Booking_no") & "" & "');", True)
                Return False
            End If
            If (txtTimeEnd.Text.Trim().Replace(":", "") = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเวลาสิ้นสุดของ Booking no. " & gridShifting.DataKeys(i).Values("Booking_no") & "" & "');", True)
                Return False
            End If
            If (CDate(txtDateg.Text) > CDate(txtDateTog.Text)) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ช่วงเวลารายการ Booking no. " & gridShifting.DataKeys(i).Values("Booking_no") & "" & " ไม่ถูกต้อง');", True)
                Return False
            End If
            Dim dr As DataRow = dt.NewRow()
            dr.Item("Booking_no") = gridShifting.DataKeys(i).Values("Booking_no")
            dr.Item("Shifting_ID") = gridShifting.DataKeys(i).Values("Shifting_ID")
            dr.Item("BookingWharf") = ddlWharfg.SelectedValue
            dr.Item("DateStart") = txtDateg.Text
            dr.Item("DateEnd") = txtDateTog.Text
            'Try
            '    dr.Item("DateStart") = CDate(txtDateg.Text).ToString("dd/MM/yyyy")
            'Catch ex As Exception
            '    dr.Item("DateStart") = "29/02/" & txtDateg.Text.Split(" ")(2)
            'End Try
            'Try
            '    dr.Item("DateEnd") = CDate(txtDateTog.Text).ToString("dd/MM/yyyy")
            'Catch ex As Exception
            '    dr.Item("DateEnd") = "29/02/" & txtDateTog.Text.Split(" ")(2)
            'End Try

            dr.Item("TimeStart") = txtTimeStart.Text
            dr.Item("TimeEnd") = txtTimeEnd.Text
            dr.Item("Remark") = txtRemark.Text
            dt.Rows.Add(dr)
            dt.AcceptChanges()
        Next
        ViewState("DataShifting") = dt
        Return True
    End Function

    Private Function CreateDataTable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("Booking_no", GetType(String))
        dt.Columns.Add("Shifting_ID", GetType(String))
        dt.Columns.Add("BookingWharf", GetType(String))
        dt.Columns.Add("DateStart", GetType(String))
        dt.Columns.Add("DateEnd", GetType(String))
        dt.Columns.Add("TimeStart", GetType(String))
        dt.Columns.Add("TimeEnd", GetType(String))
        dt.Columns.Add("Remark", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Function GenBody(ByVal str As String, ByVal booking_no As String, ByVal Agent As String, ByVal Vessel As String, ByVal Laycan As String, ByVal Wharf As String, ByVal Berth As String, ByVal Depart As String) As String
        Dim HTML As String = ""
        HTML = "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td align='left'><font class='White-Style' font-weight:bold style='color:#000000'>" & str & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"

        HTML &= "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Booking No. :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & booking_no & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Sold To :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Agent & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Vessel :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Vessel & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Lay Can\Lay Day :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Laycan & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>WHARF :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Wharf & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>PLAN BERTH :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Berth & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>PLAN DEPART :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Depart & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"
        Return HTML
    End Function

    Private Function SendMail(ByVal mail As String, ByVal Body As String) As Boolean
        Dim test As String = clsFc.sendmail(mail, "", "iPORT", Body, "")
        If (test <> "") Then
            Return True
        Else
            Return False
        End If
    End Function

    Protected Sub btnNewShifting_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnNewShifting.Click
        Dim dtNew As DataTable = CloneBookingShiftingSchema()
        Dim drNew As DataRow = dtNew.NewRow()
        drNew("Shifting_ID") = String.Empty
        dtNew.Rows.Add(drNew)
        Dim dtTmp As DataTable = ViewState("dtShift")

        'Collecting product for new row.
        Dim shiftingList As New List(Of Shifting)()
        Dim port As String = gridShifting.DataKeys(0)("PORT").ToString()
        For Each gvr As GridViewRow In gridShifting.Rows
            If (gvr.RowType = DataControlRowType.DataRow) Then
                'For Each c As Control In gvr.Controls
                '    For Each cx As Control In c.Controls
                '        msg.Text &= cx.GetType().ToString() & "," & cx.ID & "<br>"
                '    Next
                'Next
                Dim shiftingItem As New Shifting()
                Dim pro = gvr.FindControl("product")
                Dim ddlWharfTmp As DropDownList = CType(gvr.FindControl("ddlWharf"), DropDownList)
                shiftingItem.WharfID = ddlWharfTmp.SelectedValue

                Dim txtDateTmp As TextBox = CType(gvr.FindControl("txtDate"), TextBox)
                shiftingItem.DateStart = txtDateTmp.Text

                Dim txtTimeBookingStartTmp As TextBox = CType(gvr.FindControl("txtTimeBookingStart"), TextBox)
                shiftingItem.TimeStart = txtTimeBookingStartTmp.Text

                Dim txtDateToTmp As TextBox = CType(gvr.FindControl("txtDateTo"), TextBox)
                shiftingItem.DateEnd = txtDateToTmp.Text

                Dim txtTimeBookingEndTmp As TextBox = CType(gvr.FindControl("txtTimeBookingEnd"), TextBox)
                shiftingItem.TimeEnd = txtTimeBookingEndTmp.Text

                Dim txtRemarkTmp As TextBox = CType(gvr.FindControl("txtRemark"), TextBox)
                shiftingItem.Remark = txtRemarkTmp.Text



                Dim proL As New List(Of Product)
                If (pro.GetType() Is GetType(CheckBoxList)) Then

                    Dim proList As CheckBoxList = CType(pro, CheckBoxList)
                    For Each proItem As ListItem In proList.Items
                        Dim proD As New Product()
                        If (proItem.Selected) Then
                            proD.ProductID = proItem.Value
                            proD.ProductName = proItem.Text

                            Dim txtVolTmp As TextBox = CType(gvr.FindControl("vol" & proD.ProductID), TextBox)
                            proD.ProductVolume = txtVolTmp.Text
                            proL.Add(proD)
                            'msg.Text &= proItem.Value & "<br>"
                        Else
                            proL.Add(proD)
                        End If
                    Next
                Else
                    Dim proD As New Product()
                    Dim proLabel As Label = CType(pro, Label)
                    proD.ProductName = proLabel.Text
                    Dim proIdHide As HiddenField = CType(gvr.FindControl("proIdHide"), HiddenField)
                    proD.ProductID = proIdHide.Value
                    Dim proVol As TextBox = CType(gvr.FindControl("vol"), TextBox)
                    proD.ProductVolume = proVol.Text
                    proL.Add(proD)
                End If
                shiftingItem.Product = proL.ToArray()
                shiftingList.Add(shiftingItem)
                'Dim txtVol As TextBox = CType(gvr.FindControl("txtVolume"), TextBox)
                'Dim shifting As New Shifting()
                'shifting.ProductVolume = txtVol.Text
                'shiftingList.Add(shifting)
            End If

        Next
        ViewState("ShiftingClass") = shiftingList
        Dim dtShiftTmp As DataTable = dtTmp.Copy()
        dtShiftTmp.Merge(dtNew)
        'Dim BookingNo As String = ViewState("Shifting")
        'Dim dtShifting As DataSet = clsGet.Get_BookingShiftingNewRow(BookingNo)
        gridShifting.DataSource = dtShiftTmp
        gridShifting.DataBind()
        ViewState("dtShift") = dtShiftTmp

        ' msg.Text = shiftingList.Count.ToString()
        SetPrevData()


    End Sub
    Protected Sub SetPrevData()
        Dim shiftingList As List(Of Shifting) = CType(ViewState("ShiftingClass"), List(Of Shifting))
        Dim productDelList As New List(Of Product)
        If Not (ViewState("shiftingProductDel") Is Nothing) Then
            productDelList = CType(ViewState("shiftingProductDel"), List(Of Product))
        End If
        Dim hasDelProduct As Boolean = False
        If (productDelList.Count > 0) Then
            hasDelProduct = True
        End If
        For Each gvr As GridViewRow In gridShifting.Rows
            If (gvr.RowType = DataControlRowType.DataRow) Then

                Try
                    'txtVol.Text = shiftingList(gvr.RowIndex).ProductVolume
                    'ViewState("shiftingProductDel")

                    Dim shiftingItem As New Shifting()
                    shiftingItem = shiftingList(gvr.RowIndex)

                    Dim ddlWharfTmp As DropDownList = CType(gvr.FindControl("ddlWharf"), DropDownList)
                    ddlWharfTmp.ClearSelection()
                    ddlWharfTmp.Items.FindByValue(shiftingItem.WharfID).Selected = True

                    Dim txtDateTmp As TextBox = CType(gvr.FindControl("txtDate"), TextBox)
                    Dim txtTimeBookingStartTmp As TextBox = CType(gvr.FindControl("txtTimeBookingStart"), TextBox)
                    Dim txtDateToTmp As TextBox = CType(gvr.FindControl("txtDateTo"), TextBox)
                    Dim txtTimeBookingEndTmp As TextBox = CType(gvr.FindControl("txtTimeBookingEnd"), TextBox)
                    Dim txtRemarkTmp As TextBox = CType(gvr.FindControl("txtRemark"), TextBox)

                    txtDateTmp.Text = shiftingItem.DateStart
                    txtTimeBookingStartTmp.Text = shiftingItem.TimeStart
                    txtDateToTmp.Text = shiftingItem.DateEnd
                    txtTimeBookingEndTmp.Text = shiftingItem.TimeEnd
                    txtRemarkTmp.Text = shiftingItem.Remark

                    Dim pro = gvr.FindControl("product")
                   
                    Dim Shifting_ID As String = gridShifting.DataKeys(gvr.RowIndex)("Shifting_ID").ToString()
                    If (TypeOf (pro) Is CheckBoxList) Then
                        'msg.Text = "row:" & gvr.RowIndex.ToString() & "<br>"
                        Dim proList As CheckBoxList = CType(pro, CheckBoxList)
                        For Each proItem As ListItem In proList.Items
                            'msg.Text &= "ProductID:" & shiftingItem.Product(ind).ProductID.ToString() & ",ListItem ID:" & proItem.Value & "<br>"
                            For Each proItemSelect As Product In shiftingItem.Product
                                Dim proId As String = proItemSelect.ProductID
                                Dim proVol As Double = CDbl(proItemSelect.ProductVolume)
                                If (Shifting_ID = "00000" And hasDelProduct) Then
                                    Dim proDel = From pDel As Product In productDelList Where pDel.ProductID = proId Select pDel
                                    If (proDel.Count() > 0) Then
                                        proVol += CDbl(proDel(0).ProductVolume)
                                    End If
                                End If
                                If (proItem.Value = proItemSelect.ProductID) Then
                                    proItem.Selected = True
                                    Dim txtVolTmp As TextBox = CType(gvr.FindControl("vol" & proItemSelect.ProductID), TextBox)
                                    txtVolTmp.Text = proVol
                                End If
                            Next
                        Next
                    Else
                        Dim proVol As Double = CDbl(shiftingItem.Product(0).ProductVolume)
                        Dim proId As String = shiftingItem.Product(0).ProductID
                        If (Shifting_ID = "00000") Then
                            Dim proDel = From pDel As Product In productDelList Where pDel.ProductID = proId Select pDel
                            If (proDel.Count() > 0) Then
                                proVol += CDbl(proDel(0).ProductVolume)
                            End If
                        End If
                        Dim txtVolTmp As TextBox = CType(gvr.FindControl("vol"), TextBox)
                        txtVolTmp.Text = proVol
                    End If


                Catch ex As Exception

                End Try
            End If
        Next
    End Sub
    Private Sub gridShifting_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gridShifting.RowDeleting
        Dim dtShift As DataTable = CType(ViewState("dtShift"), DataTable)
        ' Dim shiftingList As List(Of Shifting) = CType(ViewState("ShiftingClass"), List(Of Shifting))
        Dim shiftingList As New List(Of Shifting)
        For Each gvr As GridViewRow In gridShifting.Rows
            If (gvr.RowType = DataControlRowType.DataRow) Then
                Dim shiftingItem As New Shifting()

                Dim ddlWharfTmp As DropDownList = CType(gvr.FindControl("ddlWharf"), DropDownList)
                shiftingItem.WharfID = ddlWharfTmp.SelectedValue

                Dim pro = gvr.FindControl("product")
                ' msg.Text &= pro.GetType().ToString() & "<br>"
                Dim products As New List(Of Product)
                If (TypeOf (pro) Is CheckBoxList) Then
                    Dim proList As CheckBoxList = CType(pro, CheckBoxList)
                    For Each proItem As ListItem In proList.Items
                        If (proItem.Selected) Then
                            Dim product As New Product()
                            Dim proId As String = proItem.Value
                            Dim proVolTmp As TextBox = CType(gvr.FindControl("vol" & proId), TextBox)
                            product.ProductID = proId
                            product.ProductVolume = proVolTmp.Text
                            products.Add(product)
                        End If
                    Next

                ElseIf (TypeOf (pro) Is Label) Then
                    Dim product As New Product()
                    Dim proIdHideTmp As HiddenField = CType(gvr.FindControl("proIdHide"), HiddenField)
                    Dim proVolTmp As TextBox = CType(gvr.FindControl("vol"), TextBox)
                    product.ProductID = proIdHideTmp.Value
                    product.ProductVolume = proVolTmp.Text
                    products.Add(product)
                End If

                shiftingItem.Product = products.ToArray()

                ViewState("shiftingProductDel") = products

                Dim txtDateTmp As TextBox = CType(gvr.FindControl("txtDate"), TextBox)
                Dim txtTimeBookingStartTmp As TextBox = CType(gvr.FindControl("txtTimeBookingStart"), TextBox)
                Dim txtDateToTmp As TextBox = CType(gvr.FindControl("txtDateTo"), TextBox)
                Dim txtTimeBookingEndTmp As TextBox = CType(gvr.FindControl("txtTimeBookingEnd"), TextBox)
                Dim txtRemarkTmp As TextBox = CType(gvr.FindControl("txtRemark"), TextBox)

                shiftingItem.DateStart = txtDateTmp.Text
                shiftingItem.TimeStart = txtTimeBookingStartTmp.Text
                shiftingItem.DateEnd = txtDateToTmp.Text
                shiftingItem.TimeEnd = txtTimeBookingEndTmp.Text
                shiftingItem.Remark = txtRemarkTmp.Text

                shiftingList.Add(shiftingItem)
            End If
           
        Next

        dtShift.Rows(e.RowIndex).Delete()
        dtShift.AcceptChanges()
        gridShifting.DataSource = dtShift
        gridShifting.DataBind()
        ViewState("dtShift") = dtShift
        Try
            shiftingList.RemoveAt(e.RowIndex)
        Catch ex As Exception

        End Try

        ViewState("ShiftingClass") = shiftingList

        ''msg.Text = "dtShift:" & dtShift.Rows.Count.ToString()
        ''msg.Text &= "<br>shiftingList:" & shiftingList.Count.ToString()
        SetPrevData()
    End Sub
End Class


